package com.usc.csci588.chaltrojan.login;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.usc.csci588.chaltrojan.R;

public class ViewMyTripsActivity extends Activity {

	//String[] current_trips;
	String[] tripName;
	String[] destName;
	String[] tripDate;
	String[] tripPwd;
	String[] active;		
	double[] lat;
	double[] lng;			
			
	
	public String xmlResponse;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_trips_layout);
		Log.d("MyView","View activity started.");
		// current_trips = new String[5];
		// for(int i=0;i<5;i++)
		// current_trips[i] = "Varun K Trip "+ i;
		getCurrentTrips();
		// setupViewMenu();

	}

	public String generateGetRequestGetTripForm(String handle) {
		//
		// http://ec2-23-22-128-131.compute-1.amazonaws.com:8080/ChalTrojan2/GetTrips?handle=suyogkotecha
		String getRequestURL = Constants.ChalTrojanHostName
				+ "/ChalTrojan2/AllDetails?handle=" + handle;
		return getRequestURL;
	}

	public String executeGetRequest(String getURL) {
		Log.d("ViewTrip", "Executing the Get request");
		String responseStr = "";
		HttpClient httpClient = new DefaultHttpClient();
		//
		HttpGet httpGet = new HttpGet(getURL);
		try {
			HttpResponse response = httpClient.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				entity.writeTo(out);
				out.close();
				responseStr = out.toString();
				// do something with response
			} else {
				responseStr = "Could not connect.";
			}
		} catch (ClientProtocolException e) {
			// handle exception
		} catch (IOException e) {
			// handle exception
		}

		Log.d("newTrip", responseStr);
		return responseStr;
	}

	void getCurrentTrips() {
		SharedPreferences settings = getSharedPreferences("HANDLE",0);
		String handle = settings.getString("handle", "default_user");		
		String getRequest = generateGetRequestGetTripForm(handle);
		Log.d("MyView", getRequest);
		GetMyTrips sc = new GetMyTrips();
		sc.execute(getRequest);
	}

	public void setupViewMenu() {

		setContentView(R.layout.view_trips_layout);
		Log.d("view", "Will set the menu now.");

		ListView lv = (ListView) findViewById(R.id.trip_list_view);
		ArrayAdapter<String> trip_view_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, tripName);
		lv.setAdapter(trip_view_adapter);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				String selectedTripName = ((TextView) view).getText().toString();				
				
				AlertDialog.Builder adb = new AlertDialog.Builder(ViewMyTripsActivity.this);			
		        adb.setTitle("Trip Details");	        
		        adb.setPositiveButton("Ok",null);
		        
		        if (selectedTripName== ""){
		        	//adb.setMessage("Are you sure you want to go here?");       	
		        	
		        } else {
		        	
		        	int len = tripName.length;
		        	int i;
		        	for(i = 0;i<len;i++)
		        	{
		        		if(selectedTripName.equals(tripName[i]))
        				{
		        			break;
        				}
		        	}       	
		        	
		        	String msg = "TripName: "+ selectedTripName +" \npassword = "+tripPwd[i]+" \nTrip Date = " + tripDate[i];		        			
		        	adb.setMessage(msg);   	
		        	
		        	
		        }
		        AlertDialog dialog = adb.create();		        
		        dialog.show();
		        //adb.setNegativeButton("Cancel", null);
		        	/*new DialogInterface.OnClickListener(){
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// ok pressed.. Go back to the list.

						}

		        	}
		        );
*/		        
		        			
				

			}
		});

	}

	private class GetMyTrips extends AsyncTask<String, Void, Void> {
		ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pd = ProgressDialog.show(ViewMyTripsActivity.this,
					"Finding your trips", "Fetching data..");
		}

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			String request = params[0];
			try {

				DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder documentBuilder = documentBuilderFactory
						.newDocumentBuilder();
				Document document = documentBuilder.parse(request);
				Log.d("MyView", "Got here.");
				NodeList ownedtripList = document.getElementsByTagName("owned");
			  	Node node = ownedtripList.item(0);			  
				Element tripElement = (Element) node;
				NodeList tripList= tripElement.getElementsByTagName("trip");				
				
				int len = tripList.getLength();
				Log.d("MyView", "My Trip Length is " + len);
				
				if (len == 0) {
					tripName = new String[1];
					tripName[0] = "No Trips Found.";
				} else {
					//len = 5;
					//current_trips = new String[len];
					tripName = new String[len];
					destName = new String[len];
					tripDate = new String[len];
					tripPwd = new String[len];
					active = new String[len];
					lat = new double[len];
					lng = new double[len];
					
					
					//current_trips = new String[len];
					for (int i = 0; i < len; i++) {
						//	current_trips[i] = "abcd"+i;
						
						
						  	Node tripNode = tripList.item(i);	  
						  	Element locationElement = (Element) tripNode;
						  	
							NodeList tripNameList = locationElement.getElementsByTagName("tripName");
							Node tripNameNode = tripNameList.item(0);
					
							
							NodeList destNameList = locationElement.getElementsByTagName("destName");
							Node destNameNode = destNameList.item(0);
							
							NodeList dateList = locationElement.getElementsByTagName("tripDate");
							Node dateNode = dateList.item(0);
							
							NodeList tripPasswordList = locationElement.getElementsByTagName("tripPwd");
							Node tripPassNode = tripPasswordList.item(0);
							
							//NodeList tripStatusList = locationElement.getElementsByTagName("active");			
													
							NodeList destLatList = locationElement.getElementsByTagName("lang");
							Node destLatNode = destLatList.item(0); 
							
							NodeList destLongList = locationElement.getElementsByTagName("long");
							Node destLongNode = destLongList.item(0);
							
											
							tripName[i] = tripNameNode.getTextContent();		 
							destName[i] = destNameNode.getTextContent();
							tripDate[i] = dateNode.getTextContent();
							tripPwd[i] = tripPassNode.getTextContent();
							//active[i] = 
							lat[i] = Double.parseDouble(destLatNode.getTextContent());
							lng[i] = Double.parseDouble(destLongNode.getTextContent());											  
							
							//current_trips[i] = node.getTextContent();
						 	  
	
					}

				}
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pd.dismiss();
			setupViewMenu();
		}

	}

}
